package opt

import (
	"fmt"
	"os"
)

func WriteFile(filePath string, context string) {
	f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_SYNC|os.O_APPEND, 0644)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	n, _ := f.WriteString(context)
	if n != len(context) {
		fmt.Println("写入错误")
	}
}

type FileName uint8

const (
	FileInfo FileName = iota
	FileErr
	FileRegister
)

var fdList map[FileName]*os.File

func InitFd(filePaths []map[FileName]string) {
	fdList = make(map[FileName]*os.File)
	for _, v := range filePaths {
		for name, val := range v {
			f, err := os.OpenFile(val, os.O_WRONLY|os.O_CREATE|os.O_SYNC|os.O_APPEND, 0644)
			if err != nil {
				fmt.Println("初始化文件发生异常")
				os.Exit(1)
			}
			fdList[name] = f
		}
	}

}

func Write(fileName FileName, fileContext string) {
	if v, ok := fdList[fileName]; !ok {
		fmt.Println("错误的文件名")
		return
	} else {
		v.WriteString(fileContext)
	}
}

func CloseFiles() {
	for _, v := range fdList {
		v.Close()
	}
}
